package com.wuliu.common.utils;

import com.wuliu.common.enums.RedisDelayQueueEnum;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedissonUtils {

    @Autowired
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * lock(), 拿不到lock就不罢休，不然线程就一直block
     */
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * leaseTime为加锁时间，单位为秒 如果是-1，直到自己解锁，否则不会自动解锁
     */
    public RLock lock(String lockKey, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * timeout为加锁时间，时间单位由unit确定
     */
    public RLock lock(String lockKey, TimeUnit unit, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     * tryLock()，马上返回，拿到lock就返回true，不然返回false。
     * 带时间限制的tryLock()，拿不到lock，就等一段时间，超时返回false.
     */
    public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 释放 key 的锁
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    /**
     * 释放锁
     */
    public void unlock(RLock lock) {
        lock.unlock();
    }

    /**
     * 添加延迟队列
     *
     * @param value     队列值
     * @param queueName 队列键
     * @param <T>
     */
    public <T> void addDelayQueue(T value, String queueName) {
        try {
            long delay = RedisDelayQueueEnum.getDelayByName(queueName);
            TimeUnit timeUnit = RedisDelayQueueEnum.getTimeUnitByName(queueName);
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueName);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.offer(value, delay, timeUnit);
            assert timeUnit != null;
            log.info("添加延时队列成功->队列键：{}，队列值：{}，延迟时间：{}", queueName, value, timeUnit.toSeconds(delay) + "秒");
        } catch (Exception e) {
            log.error("添加延时队列失败->{}", e.getMessage());
            throw new RuntimeException("添加延时队列失败");
        }
    }

    /**
     * 获取延迟队列
     *
     * @param queueCode
     * @param <T>
     * @return
     * @throws InterruptedException
     */
    public <T> T getDelayQueue(String queueCode) throws InterruptedException {
        RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);
        //解决应用重启，无法消费的情况
        redissonClient.getDelayedQueue(blockingDeque);
        return (T) blockingDeque.take();
    }


    /**
     * 移除延迟队列数据
     *
     * @param value     队列值
     * @param queueName 队列键
     * @param <T>
     */
    public <T> void removeDelayQueue(T value, String queueName) {
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueName);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.remove(value);
            log.info("移除延迟队列数据成功->队列键：{}，队列值：{}", queueName, value);
        } catch (Exception e) {
            log.error("移除延迟队列数据失败->{}", e.getMessage());
            throw new RuntimeException("移除延迟队列数据失败");
        }
    }
}
